package com.longcai.piaojia.dialog;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.longcai.piaojia.R;
import com.longcai.piaojia.activity.MyReceiveAddressAddActivity;
import com.longcai.piaojia.beans.AreaEntity;
import com.longcai.piaojia.beans.CityEntity;
import com.longcai.piaojia.beans.ProvinceEntity;
import com.longcai.piaojia.widget.wheel.widget.OnWheelChangedListener;
import com.longcai.piaojia.widget.wheel.widget.WheelView;
import com.longcai.piaojia.widget.wheel.widget.adapters.ArrayWheelAdapter;
import com.zcx.helper.app.AppCallBack;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/29.
 */
public abstract class ChooseAreaDialog extends BaseDialog implements OnWheelChangedListener {

    private Context context;

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;

    private List<ProvinceEntity> provinceEntities = new ArrayList<ProvinceEntity>();

    private String[] provinceEntity;
    private String[] cityEntity;
    private String[] areaEntity;

    protected Map<String, ProvinceEntity> provinceMap = new HashMap<String, ProvinceEntity>();
    protected Map<String, CityEntity> cityMap = new HashMap<String, CityEntity>();
    protected Map<String, AreaEntity> areaMap = new HashMap<String, AreaEntity>();
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    protected String mCurrentProviceName;
    protected String mCurrentCityName;
//    protected String mCurrentDistrictName = "";
//    protected String mCurrentZipCode = "";

    public ChooseAreaDialog(final Context context) {

        super(context);

        this.context = context;
        setContentView(R.layout.dialog_choose_area);

        View.OnClickListener onClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int pCurrent = mViewDistrict.getCurrentItem();

                String areaName = "";
                String areaId = "";

                try {

                    areaName = mDistrictDatasMap.get(mCurrentCityName)[pCurrent];
                    areaId = areaMap.get(cityMap.get(mCurrentCityName).region_id + areaName).region_id;

                } catch (NullPointerException e) {

                }

                switch (v.getId()) {

                    case R.id.dialog_choose_area_confirm_tv:

                        onConfirm(provinceMap.get(mCurrentProviceName).region_name, provinceMap.get(mCurrentProviceName).region_id, cityMap.get(mCurrentCityName).region_name,cityMap.get(mCurrentCityName).region_id,areaName, areaId);

                        break;

                    case R.id.dialog_choose_area_cancle_tv:
                        break;

                }

                dismiss();

            }

        };

        findViewById(R.id.dialog_choose_area_confirm_tv).setOnClickListener(onClickListener);
        findViewById(R.id.dialog_choose_area_cancle_tv).setOnClickListener(onClickListener);

        setUpViews();
        setUpListener();
        findViews();
        setUpData();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) findViewById(R.id.dialog_choose_area_ll));

        getWindow().setGravity(Gravity.BOTTOM);
    }

    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
    }

    private void setUpListener() {
        // ���change�¼�
        mViewProvince.addChangingListener(this);
        // ���change�¼�
        mViewCity.addChangingListener(this);
        // ���change�¼�
        mViewDistrict.addChangingListener(this);
        // ���onclick�¼�
    }

    private void setUpData() {
        ArrayWheelAdapter arrayWheelAdapter = new ArrayWheelAdapter<String>(context, provinceEntity);
        mViewProvince.setViewAdapter(arrayWheelAdapter);
        // ���ÿɼ���Ŀ����
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    private void findViews() {
        AssetManager asset = context.getResources().getAssets();
        InputStream is;
        try {
            is = asset.open("region.txt");
            int size = is.available();// 取得数据流的数据大小
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String txt = new String(buffer);

            try {
                JSONObject jsonObject = new JSONObject(txt);

                JSONArray jsonArray = jsonObject.optJSONArray("data");

                provinceEntity = new String[1];

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject_Province = jsonArray.optJSONObject(i);

                    String province_name = jsonObject_Province.optString("region_name");

                    if(province_name.equals("黑龙江省")){

                        provinceEntity[0] = province_name;

                        ProvinceEntity provinceEntity = new ProvinceEntity();
                        provinceEntity.region_id = jsonObject_Province.optString("region_id");
                        provinceEntity.parent_id = jsonObject_Province.optString("parent_id");
                        provinceEntity.region_name = province_name;
                        provinceEntity.region_type = jsonObject_Province.optString("region_type");

                        provinceMap.put(province_name, provinceEntity);

                        JSONArray jsonArray_City = jsonObject_Province
                                .optJSONArray("city");

                        cityEntity = new String[1];

                        for (int j = 0; j < jsonArray_City.length(); j++) {

                            JSONObject jsonObject_City = jsonArray_City
                                    .optJSONObject(j);

                            String city_name = jsonObject_City
                                    .optString("region_name");

                            if(city_name.equals("哈尔滨市")){

                                cityEntity[0] = city_name;
                                mCitisDatasMap.put(province_name, cityEntity);

                                CityEntity cityEntity = new CityEntity();
                                cityEntity.region_id = jsonObject_City.optString("region_id");
                                cityEntity.parent_id = jsonObject_City.optString("parent_id");
                                cityEntity.region_name = city_name;
                                cityEntity.region_type = jsonObject_City.optString("region_type");

                                cityMap.put(city_name, cityEntity);
                                provinceEntity.city.add(cityEntity);

                                JSONArray jsonArray_Area = jsonObject_City.optJSONArray("area");

                                areaEntity = new String[jsonArray_Area.length()];

                                for (int k = 0; k < jsonArray_Area.length(); k++) {

                                    JSONObject jsonObject_Area = jsonArray_Area.optJSONObject(k);

                                    String area_name = jsonObject_Area.optString("region_name");

                                    areaEntity[k] = area_name;
                                    mDistrictDatasMap.put(city_name, areaEntity);

                                    AreaEntity areaEntity = new AreaEntity();
                                    areaEntity.region_id = jsonObject_Area.optString("region_id");
                                    areaEntity.parent_id = jsonObject_Area.optString("parent_id");
                                    areaEntity.region_name = area_name;
                                    areaEntity.region_type = jsonObject_Area.optString("region_type");

                                    areaMap.put(jsonObject_City.optInt("region_id") + area_name, areaEntity);

                                    provinceEntity.city.get(j).area.add(areaEntity);

                                }

                            }

                            provinceEntities.add(provinceEntity);

                        }

                    }

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // 获得AssetManger 对象, 调用其open 方法取得 对应的inputStream对象

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        }
//        else if (wheel == mViewDistrict) {
//            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
//            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
//        }
    }

    /**
     * ���ݵ�ǰ���У�������WheelView����Ϣ
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];

        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict
                .setViewAdapter(new ArrayWheelAdapter<String>(context, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * ���ݵ�ǰ��ʡ��������WheelView����Ϣ
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = provinceEntity[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }



    private void showSelectedResult() {

        int pCurrent = mViewDistrict.getCurrentItem();

        String areaName = mDistrictDatasMap.get(mCurrentCityName)[pCurrent];

        Toast.makeText(
                context,
                "点击结果:" + provinceMap.get(mCurrentProviceName).region_id + "," + cityMap.get(mCurrentCityName).region_id + ","
                        + areaMap.get(cityMap.get(mCurrentCityName).region_id + areaName).region_id,
                Toast.LENGTH_SHORT).show();
    }

    public abstract void onConfirm(String province, String provinceId, String city, String cityId, String area, String areaId);

}
